<template>
  <v-container>
    <v-card class="mt-4">
      <v-card-title class="d-flex justify-space-between align-center">
        <span class="headline">逻辑结构可视化</span>
        <span class="essay-type" v-if="genre">{{ genre }}</span>
      </v-card-title>

      <v-row class="mt-4">
        <v-col cols="12">
          <v-card class="pa-4">
            <div ref="logicStructureChart" style="width: 100%; height: 500px;"></div>
          </v-card>
        </v-col>
      </v-row>
    </v-card>
  </v-container>
</template>



<script>
import * as echarts from "echarts";
import { chat } from "@/api/job";
import { mapGetters } from "vuex";

export default {
  name: "LogicalStructureAnalysis",
  props: {
    essayCategory: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      logicData: null,
      genre: ""        // ✅ 用于具体体裁识别（如：道歉信、议论文等）
    };
  },
  computed: {
    ...mapGetters(["userEssay"])
  },
  watch: {
    /**
     * 监听 `userEssay` 变化
     */
    userEssay(newEssay) {
      console.log("userEssay 更新：", newEssay);

      if (newEssay && newEssay.trim()) {
        this.detectEssayGenre(newEssay, this.essayCategory);
      } else {
        this.clearChart();
        this.genre = "";
      }
    },

    /**
     * 监听 `essayCategory` 变化
     */
    essayCategory(newCategory) {
      console.log("essayCategory 更新：", newCategory);

      if (this.userEssay && this.userEssay.trim()) {
        this.detectEssayGenre(this.userEssay, newCategory);
      }
    }
  },
  methods: {
    /**
     * 1. 识别具体体裁（如：道歉信、议论文等）
     */
    async detectEssayGenre(essayText, essayCategory) {
      if (!essayText || !essayText.trim()) {
        console.warn("作文内容为空，无法分析");
        this.genre = "";
        this.clearChart();
        return;
      }

      if (!essayCategory) {
        console.warn("作文类型为空，无法分析");
        return;
      }

      console.log("开始识别体裁：", essayText, essayCategory);

      try {
        let prompt = "";

        if (essayCategory === "小作文") {
          prompt = `根据以下小作文内容，判断其具体体裁，仅返回体裁类型（如：邀请信、建议信、感谢信、投诉信）：\n\n${essayText}`;
        } else if (essayCategory === "大作文") {
          prompt = `根据以下大作文内容，判断其具体体裁，仅返回体裁类型（如：议论文、说明文、图表作文、图画作文）：\n\n${essayText}`;
        }

        const response = await chat(prompt);
        const detectedGenre = response.data.response.trim();
        console.log("识别出的具体体裁：", detectedGenre);

        this.genre = detectedGenre;
        this.analyzeEssayStructure(essayText, detectedGenre);

      } catch (error) {
        console.error("体裁识别失败：", error);
        this.genre = "识别失败";
        this.clearChart();
      }
    },

    /**
     * 2. 生成逻辑结构
     */
    async analyzeEssayStructure(essayText, genre) {
      try {
        const structurePrompt = `
          根据体裁 "${genre}"，为以下作文内容生成逻辑结构树：
          - 数据格式：一级节点：二级节点
          - 保持简洁，不要冗长说明

          作文内容：
          ${essayText}
        `;

        const response = await chat(structurePrompt);
        const structureData = response.data.response.trim().split("\n");

        console.log("逻辑结构数据：", structureData);

        this.logicData = this.formatStructureData(structureData);
        this.generateLogicChart(this.logicData);

      } catch (error) {
        console.error("逻辑结构分析失败：", error);
        this.clearChart();
      }
    },

    /**
     * 3. 格式化逻辑结构数据
     */
    formatStructureData(data) {
      const formattedData = {
        name: this.genre,
        children: []
      };

      data.forEach(line => {
        const parts = line.split("：");
        if (parts.length === 2) {
          formattedData.children.push({
            name: parts[0],
            children: [{ name: parts[1] }]
          });
        }
      });

      return formattedData;
    },

    /**
     * 4. 渲染逻辑树图
     */
    generateLogicChart(data) {
      const chartElement = this.$refs.logicStructureChart;
      const chart = echarts.init(chartElement);

      const option = {
        backgroundColor: '#fafafa',
        tooltip: { trigger: 'item', formatter: '{b}' },
        series: [
          {
            type: 'tree',
            data: [data],
            layout: 'orthogonal',
            symbol: 'circle',
            symbolSize: 25,
            initialTreeDepth: 2,
            label: {
              position: 'left',
              verticalAlign: 'middle',
              align: 'right',
              fontSize: 14,
              color: '#333'
            },
            itemStyle: {
              color: '#4FC3F7',
              borderWidth: 2,
              borderColor: '#0288D1'
            },
            lineStyle: { color: '#81D4FA', width: 2, curveness: 0.5 },
            expandAndCollapse: true,
            animationDuration: 800,
            animationEasing: 'bounceOut'
          }
        ]
      };

      chart.setOption(option);
    },

    /**
     * 5. 清空图表
     */
    clearChart() {
      const chartElement = this.$refs.logicStructureChart;
      const chart = echarts.init(chartElement);
      chart.clear();
      this.logicData = null;
    }
  }
};
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}

.pa-4 {
  padding: 16px;
}

.essay-type {
  font-size: 16px;
  font-weight: bold;
  color: #0288D1;
  background-color: #E1F5FE;
  padding: 4px 8px;
  border-radius: 4px;
}

</style>
